package com.pcbly.web.components.interceptor;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.pcbly.web.Constants;
import com.pcbly.web.bean.user.UserSession;
import com.pcbly.web.config.SysConfig;

public class UserOnlineInterceptor extends AbstractInterceptor {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5600935142875053827L;
	private static final Log logger = LogFactory
			.getLog(UserOnlineInterceptor.class);

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		ActionContext ac = invocation.getInvocationContext();
		ServletContext servletContext = (ServletContext) ac
				.get(ServletActionContext.SERVLET_CONTEXT);
		WebApplicationContext wc = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);
		if (wc == null) {
			logger.error("ApplicationContext could not be found.");
		} else {

			UserSession us = (UserSession) ac.getSession().get(
					Constants.USER_SESSION_KEY);
			SysConfig sysConfig = (SysConfig) wc.getBean("sysConfig");
			if (!(sysConfig == null)) {
				long nowTime = System.currentTimeMillis();

				long addedTime = nowTime - us.getLastActiveTime();
				us.setOnlineTime(us.getOnlineTime() + addedTime);
				us.setOnlineHour(us.getOnlineHour() + addedTime);
				if (us.getOnlineTime() >= (sysConfig.getUserOnlineTime() * 1000 * 60)) {
					logger.debug("用户 " + us.getUserName() + " 在线累计超过"
							+ sysConfig.getUserOnlineTime() + "分钟");
					

				}
			}

		}
		return invocation.invoke();
	}

	protected UserSession createGuestUserSession(String gUestID,
			String gUesrName) {
		UserSession us = new UserSession();

		us.setId(gUestID);
		us.setNickName("Guest");
		us.setUserName(gUesrName);
		return us;
	}

}
